package com.teangtang.fly.service;
import com.teangtang.fly.dto.CabinDTO;
import com.teangtang.fly.dto.PlaneDTO;
import com.teangtang.fly.entity.Cabin;
import com.teangtang.fly.entity.Plane;
import com.teangtang.fly.repository.CabinRepository;
import com.teangtang.fly.repository.PlaneRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class PlaneService {

    @Autowired
    private PlaneRepository planeRepository;
    @Autowired
    private CabinRepository cabinRepository;

    public Plane getPlaneById(Long id) {
        return planeRepository.findById(id).orElse(null);
    }

    public PlaneDTO savePlaneByPlaneDTO(Plane plane, PlaneDTO planeDTO){
        plane.setName(planeDTO.getName());
        plane.setType(planeDTO.getType());
        // 更新 Cabin 实体
        List<Cabin> cabins = new ArrayList<>();
        for (CabinDTO cabinDTO : planeDTO.getCabins()) {
            Cabin cabin = new Cabin();
            cabin.setName(cabinDTO.getName());
            cabin.setType(cabinDTO.getType());
            cabin.setCapacity(cabinDTO.getCapacity());
            cabin.setPlane(plane);
            cabins.add(cabin);
        }
        if(plane.getCabins() != null){
            for(Cabin cabin : plane.getCabins()){
                planeRepository.deleteCabinById(cabin.getId());
            }
        }
        plane.setCabins(cabins);

        // 保存更新后的 Plane 实体
        Plane savedPlane = this.savePlane(plane);

        // 将保存后的 Plane 转换为 PlaneDTO 返回
        PlaneDTO savedPlaneDTO = new PlaneDTO();
        savedPlaneDTO.setName(savedPlane.getName());
        savedPlaneDTO.setType(savedPlane.getType());

        List<CabinDTO> savedCabinDTOs = new ArrayList<>();
        for (Cabin cabin : savedPlane.getCabins()) {
            CabinDTO cabinDTO = new CabinDTO();
            cabinDTO.setName(cabin.getName());
            cabinDTO.setType(cabin.getType());
            cabinDTO.setCapacity(cabin.getCapacity());
            savedCabinDTOs.add(cabinDTO);
        }
        savedPlaneDTO.setCabins(savedCabinDTOs);

        return savedPlaneDTO;
    }
    public Plane savePlane(Plane plane) {

        for (Cabin cabin : plane.getCabins()){
            cabin.setPlane(plane);
        }
        Plane savedPlane = planeRepository.save(plane);
        return savedPlane;
    }
    public List<Plane> getAllPlanes() {
        return planeRepository.findAll();
    }

    public void deletePlaneById(Long id) {
        planeRepository.deleteById(id);
    }
}
